// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: fengyang

#pragma once

#include <string>

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"

namespace impl {
using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;
using coin2::exchange::base::feed_util::Index;

class CryptoFeedUpdateParser {
 public:

  static void ParseBook(
      BookBuilder* book_builder,
      const rapidjson::Value& book_json) {
    int64_t timestamp = stoull(book_json["t"].GetString()) * 1'000'000LL;
    auto tx = book_builder->NewTransaction(timestamp);

    for (const auto& ask_obj : book_json["asks"].GetArray()) {
      double price = stod(ask_obj[0].GetString());
      double size = stod(ask_obj[1].GetString());
      tx.UpdateAsk(price, size);
    }

    for (const auto& bid_obj : book_json["bids"].GetArray()) {
      double price = stod(bid_obj[0].GetString());
      double size = stod(bid_obj[1].GetString());
      tx.UpdateBid(price, size);
    }
  }

  static void ParseTrade(
      const rapidjson::Value& trade_json,
      Trade* trade) {
    trade->timestamp = stoull(trade_json["t"].GetString()) * 1'000'000LL;
    trade->price = stod(trade_json["p"].GetString());
    trade->fill_qty = stod(trade_json["q"].GetString());
    std::string side = trade_json["s"].GetString();
    trade->side = ParseTradeSide(side);
  }

  static coin2::exchange::feed::TradeSide ParseTradeSide(const std::string& side) {
    if (side == "BUY") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "SELL") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else {
      throw std::runtime_error("[Crypto] unknown side: " + side);
    }
  }

  static void ParseIndex(
      const rapidjson::Value& index_json,
      Index* index) {
    CHECK(index);
    index->Clear();
    index->timestamp = stoull(index_json["t"].GetString()) * 1'000'000LL;
    index->price = stod(index_json["v"].GetString());
  }

  static void ParseMarkPrice(
      const rapidjson::Value& mark_json,
      MarkPrice* mark_price) {
    CHECK(mark_price);
    mark_price->Clear();
    mark_price->timestamp = stoull(mark_json["t"].GetString()) * 1'000'000LL;
    mark_price->mark_price = stod(mark_json["v"].GetString());
  }

  static void ParseFundingRate(
      const rapidjson::Value& fouding_json,
      FundingRate* funding_rate) {
    CHECK(funding_rate);
    funding_rate->Clear();
    funding_rate->funding_rate = stod(fouding_json["v"].GetString());
    funding_rate->funding_time = stoull(fouding_json["t"].GetString()) * 1'000'000LL;
  }

  static void ParseOpenInterest(
      const rapidjson::Value& open_interest_json,
      OpenInterest* open_interest) {
    CHECK(open_interest);
    open_interest->Clear();
    open_interest->open_interest_qty = stod(open_interest_json["oi"].GetString());
    open_interest->timestamp = stoull(open_interest_json["t"].GetString()) * 1'000'000LL;
  }

  static fastfeed::proto::KlineInterval ParseKlineInterval(std::string_view interval) {
    static std::map<std::string, fastfeed::proto::KlineInterval> interval_map = {
      {"1m", fastfeed::proto::KLINE_INTERVAL_1MIN},
      {"3m", fastfeed::proto::KLINE_INTERVAL_3MIN},
      {"5m", fastfeed::proto::KLINE_INTERVAL_5MIN},
      {"15m", fastfeed::proto::KLINE_INTERVAL_15MIN},
      {"30m", fastfeed::proto::KLINE_INTERVAL_30MIN},
      {"1h", fastfeed::proto::KLINE_INTERVAL_1HOUR},
      {"1d", fastfeed::proto::KLINE_INTERVAL_1DAY}
    };

    auto iter = interval_map.find(std::string(interval));
    if (iter == interval_map.end()) {
      return fastfeed::proto::KLINE_INTERVAL_INVALID;
    }

    return iter->second;
  }

  static bool ParseKlineRest(
      const rapidjson::Value& msg,
      Klines* klines,
      fastfeed::proto::KlineInterval interval,
      int64_t timestamp) {
    int64_t open_timestamp = stoll(msg["t"].GetString()) * 1'000'000LL;
    auto result = klines->AddKline(open_timestamp);
    if (!result) return false;

    Kline* kline;
    bool freezed;
    std::tie(kline, freezed) = result.value();
    kline->open_timestamp = open_timestamp;
    kline->open = stod(msg["o"].GetString());
    kline->high = stod(msg["h"].GetString());
    kline->low = stod(msg["l"].GetString());
    kline->close = stod(msg["c"].GetString());
    kline->volume = stod(msg["v"].GetString());
    kline->turnover = kline->volume * kline->close;
    kline->timestamp = timestamp;
    kline->interval = interval;

    return freezed;
  }
};
}  // namespace impl

using impl::CryptoFeedUpdateParser;
